<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="formData" ref="formDataRef">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-form-item label="菜单名称" prop="name">
            <el-input v-model="formData.name" placeholder="菜单名称" clearable style="width: 100%"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="菜单类型" prop="modelType">
            <el-select v-model="formData.modelType" placeholder="菜单类型" clearable style="width: 100%">
              <el-option label="单页" value="page"></el-option>
              <el-option label="列表页" value="list"></el-option>
              <el-option label="分类" value="category"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="状态" prop="status">
            <el-select v-model="formData.status" placeholder="状态" clearable style="width: 100%">
              <el-option label="正常" :value="1"></el-option>
              <el-option label="停用" :value="2"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <ButtonGroup ref="btnGroupRef" @on-search="search" @on-reset="resetSearch">
            <template v-slot:hole>
              <el-button type="primary" size="small" @click="handleAdd">新增菜单</el-button>
              <el-button type="danger" size="small" @click="handleBatchDelete" :disabled="selectedRows.length === 0">批量删除</el-button>
              <el-button type="success" size="small" @click="handleExpandAll">{{ isExpandAll ? "折叠全部" : "展开全部" }}</el-button>
            </template>
          </ButtonGroup>
        </el-col>
      </el-row>
    </el-form>

    <!-- 树形表格 -->
    <el-table
      :data="treeTableData"
      v-loading="tableLoading"
      row-key="_id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :default-expand-all="isExpandAll"
      class="mt-3 w-100"
      stripe
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" fixed="left"></el-table-column>
      <el-table-column label="序号" type="index" width="55" fixed="left"></el-table-column>
      <el-table-column label="菜单名称" prop="name" min-width="200" show-overflow-tooltip></el-table-column>
      <el-table-column label="菜单类型" prop="modelType" width="100">
        <template v-slot="{ row }">
          <el-tag :type="getModelTypeTagType(row.modelType)">
            {{ getModelTypeText(row.modelType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="80">
        <template v-slot="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? "正常" : "停用" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="外部链接" prop="isOutLink" width="100">
        <template v-slot="{ row }">
          <el-tag :type="row.isOutLink === 1 ? 'warning' : 'info'">
            {{ row.isOutLink === 1 ? "是" : "否" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="可点击" prop="clickable" width="80">
        <template v-slot="{ row }">
          <el-tag :type="row.clickable === 1 ? 'success' : 'danger'">
            {{ row.clickable === 1 ? "是" : "否" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="菜单链接" prop="link" min-width="200" show-overflow-tooltip></el-table-column>
      <el-table-column label="排序" prop="sort" width="80"></el-table-column>
      <el-table-column label="操作" width="300" fixed="right">
        <template v-slot="{ row }">
          <el-button type="primary" text @click="handleEdit(row)">编辑</el-button>
          <el-button type="primary" text @click="handlePreview(row)">预览</el-button>
          <el-button type="danger" text @click="handleDelete(row)">删除</el-button>
          <el-button type="info" text @click="handleToggleStatus(row)">
            {{ row.status === 1 ? "停用" : "启用" }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑弹窗 -->
    <Dialog ref="dialogRef" :title="dialogOptions.title" :width="dialogOptions.width" @close="handleDialogClose" @confirm="handleDialogConfirm">
      <template v-slot:content>
        <el-form :model="diaFormData" :rules="diaFormDataRules" ref="diaFormDataRef" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="菜单类型" prop="modelType">
                <el-select v-model="diaFormData.modelType" placeholder="请选择菜单类型" style="width: 100%">
                  <el-option label="单页" value="page"></el-option>
                  <el-option label="列表页" value="list"></el-option>
                  <el-option label="分类" value="category"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="父菜单" prop="parentCode">
                <el-cascader v-model="cascaderValue" :options="cascaderOptions" :props="cascaderProps" placeholder="请选择父菜单" clearable style="width: 100%" @change="handleCascaderChange" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="菜单编码" prop="code">
                <el-input v-model="diaFormData.code" disabled placeholder="请输入菜单编码"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="菜单名称" prop="name">
                <el-input v-model="diaFormData.name" placeholder="请输入菜单名称"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="diaFormData.isOutLink !== 1 && diaFormData.modelType !== 'category'">
            <el-col :span="12">
              <el-form-item label="列表页模板" v-if="diaFormData.modelType === 'list'" prop="listTplId" :rules="{ requierd: true, message: '请选择列表页模板', trigger: 'change' }">
                <el-select v-model="diaFormData.listTplId" placeholder="请选择列表页模板" @change="handleListTplIdChange">
                  <el-option v-for="item in listTemplateOptions" :label="item.templateName" :key="item._id" :value="item._id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="diaFormData.isOutLink !== 1 && diaFormData.modelType !== 'category'">
            <el-col :span="12">
              <el-form-item label="详情页面模板" prop="detailTplId">
                <el-select v-model="diaFormData.detailTplId" placeholder="请选择详情页模板" @change="handleDetailTplIdChange">
                  <el-option v-for="item in pageTemplateOptions" :label="item.templateName" :key="item._id" :value="item._id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据关联" prop="modelName">
                <el-select v-model="diaFormData.modelName" placeholder="请选择" clearable style="width: 100%" @change="handleModelNameChange">
                  <el-option v-for="module in moduleOptions" :key="module.moduleId" :label="module.moduleName" :value="module.moduleName"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="菜单链接" prop="link" :rules="{ required: true, message: '请输入菜单链接', trigger: 'blur' }">
            <el-input v-model="diaFormData.link" placeholder="请输入菜单链接"></el-input>
            <span class="font-12"
              >例如：'/news'。注意，如果选择菜单类型为'列表'，则会自动创建对应的文件夹和[id].vue文件 例如 /products/index.vue 以及 /products/[id].vue;如果选择分类，那么需要在 - 后添加，例如
              /news-some。</span
            >
            <!-- /products -->
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="是否外部链接">
                <el-select v-model="diaFormData.isOutLink" placeholder="请选择" style="width: 100%">
                  <el-option label="否" :value="0"></el-option>
                  <el-option label="是" :value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否可点击">
                <el-select v-model="diaFormData.clickable" placeholder="请选择" style="width: 100%">
                  <el-option label="否" :value="0"></el-option>
                  <el-option label="是" :value="1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="外部跳转链接" prop="outLink" v-if="diaFormData.isOutLink === 1" :rules="{ required: true, message: '请输入外部跳转链接', trigger: 'blur' }">
            <el-input v-model="diaFormData.outLink" placeholder="请输入外部跳转链接"></el-input>
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select v-model="diaFormData.status" placeholder="请选择状态" style="width: 100%">
                  <el-option label="正常" :value="1"></el-option>
                  <el-option label="停用" :value="2"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="菜单排序" v-if="diaFormData.isOutLink !== 1">
                <el-input-number v-model="diaFormData.sort" :min="1" placeholder="请输入排序值" style="width: 100%"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="标题" v-if="diaFormData.isOutLink !== 1">
            <el-input v-model="diaFormData.title" placeholder="请输入菜单标题（可选）"></el-input>
          </el-form-item>
          <el-form-item label="关键字" v-if="diaFormData.isOutLink !== 1">
            <el-input v-model="diaFormData.keywords" placeholder="请输入菜单关键字（可选）"></el-input>
          </el-form-item>
          <el-form-item label="描述" v-if="diaFormData.isOutLink !== 1">
            <el-input v-model="diaFormData.description" type="textarea" :rows="3" placeholder="请输入菜单描述（可选）"></el-input>
          </el-form-item>
          <el-row :gutter="20" v-if="diaFormData.isOutLink !== 1 && diaFormData.modelType !== 'category'">
            <el-col :span="24">
              <el-form-item label="缩略图（icon）">
                <ImageSelector type="img" v-model:imgUrl="diaFormData.icon" :preview-src-list="[diaFormData.icon]" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="大图（picture）">
                <ImageSelector type="img" v-model:imgUrl="diaFormData.picture" :preview-src-list="[diaFormData.picture]" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </Dialog>

    <!-- 分页 -->
    <el-pagination
      v-if="!isExpandAll"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pages.pageNum"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pages.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pages.total"
      class="pagination-container"
    >
    </el-pagination>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { IWebMenuType } from "#/common";
import BaseTable from "@/components/BaseTable/index.vue";
import Dialog from "@/components/Dialog/index.vue";
import ButtonGroup from "@/components/ButtonGroup/index.vue";
import { resetForm } from "@/utils/tools";
import { getWebMenuList, createWebMenu, updateWebMenu, deleteWebMenu, batchDeleteWebMenus, updateWebMenuStatus, getMenuTree } from "@/api/webmenus";
import { getAllModules, getAllTemplates } from "@/api/webbase";
import ImageSelector from "@/components/ImageSelector/index.vue";

// ------- 响应式数据 -------
const formData = ref({
  name: "",
  modelType: "",
  status: ""
});

const pages = ref({
  pageSize: 1000,
  pageNum: 1,
  total: 0
});

const tableData = ref([]);
const treeTableData = ref([]);
const tableLoading = ref(false);
const selectedRows = ref([]);
const isExpandAll = ref(false);
const pageTemplateOptions = ref<any[]>([]); // 页面模板
const listTemplateOptions = ref<any[]>([]); // 列表页模板

// 弹窗相关
const diaFormData = ref<IWebMenuType>({
  parentCode: "",
  parentName: "",
  parentLink: "",
  code: "",
  name: "",
  link: "",
  modelType: "page",
  modelId: "",
  modelName: "",
  isOutLink: 0,
  outLink: "",
  clickable: 1,
  listTplName: "",
  listTplId: "",
  detailTplName: "",
  detailTplId: "",
  icon: "",
  picture: "",
  title: "",
  keywords: "",
  description: "",
  status: 1,
  sort: 1
});

// 模块选项数据
const moduleOptions = ref<any[]>([]);

// 级联选择器相关
const cascaderOptions = ref<any[]>([]);
const cascaderValue = ref<string[]>([]);
const cascaderProps = {
  checkStrictly: true,
  value: "code",
  label: "name",
  children: "children"
};

const dialogOptions = ref({
  title: "新增菜单",
  width: "800px"
});

const isEdit = ref(false);
const editId = ref("");

// ------- refs -------
const formDataRef = ref<FormInstance>();
const diaFormDataRef = ref<FormInstance>();
const dialogRef = ref();

const btnGroupRef = ref();

// ------- 表单验证规则 -------
const diaFormDataRules = {
  parentName: [{ required: true, message: "请输入父菜单名称", trigger: "blur" }],
  name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
  modelType: [{ required: true, message: "请选择菜单类型", trigger: "change" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  modelName: [
    {
      validator: (rule: any, value: string, callback: any) => {
        // 如果菜单类型为list，模型选择是必填的
        if (diaFormData.value.modelType === "list") {
          if (!value || value.trim() === "") {
            callback(new Error("当菜单类型为列表页时，必须选择模型"));
            return;
          }
        }
        callback();
      },
      trigger: "change"
    }
  ],
  link: [
    {
      validator: (rule: any, value: string, callback: any) => {
        // 如果菜单类型为分类，不需要校验链接
        if (diaFormData.value.modelType === "category") {
          callback();
          return;
        }

        // 对于非分类类型，链接是必填的
        if (!value) {
          callback(new Error("请输入菜单链接"));
          return;
        }

        // 如果菜单类型为list，验证链接格式必须为 '/xxx'（只能有一层）
        if (diaFormData.value.modelType === "list") {
          if (!value.startsWith("/")) {
            callback(new Error("列表页菜单链接必须以'/'开头，格式如：/products"));
            return;
          }
          // 验证格式：以/开头，后面只能跟小写字母，不允许特殊符号（包括下划线、中划线等）
          const linkPattern = /^\/[a-z]+$/;
          if (!linkPattern.test(value)) {
            callback(new Error("列表页菜单链接格式不正确，只能包含字母和数字，不允许特殊符号，格式如：/products"));
            return;
          }
          // 检查是否包含多个斜杠（多层路径）
          if (value.split("/").length > 2) {
            callback(new Error("列表页菜单链接只能有一层，不允许多层嵌套路径，格式如：/products"));
            return;
          }
        }
        callback();
      },
      trigger: "blur"
    }
  ],
  parentCode: [{ required: true, message: "请选择父菜单", trigger: "change" }],
  detailTplId: [{ required: true, message: "请选择页面模板", trigger: "change" }]
};

// ------- 方法 -------

/**
 * 处理每页显示数量变化
 * @param val 新的每页显示数量
 */
const handleSizeChange = (val: number) => {
  pages.value.pageNum = 1;
  search();
};

/**
 * 处理当前页变化
 * @param val 新的当前页
 */
const handleCurrentChange = (val: number) => {
  pages.value.pageNum = val;
  search();
};

/**
 * 获取菜单类型标签类型
 * @param modelType 菜单类型
 * @returns 标签类型
 */
const getModelTypeTagType = (modelType?: string) => {
  switch (modelType) {
    case "page":
      return "primary";
    case "list":
      return "success";
    case "category":
      return "warning";
    default:
      return "info";
  }
};

/**
 * 获取菜单类型文本
 * @param modelType 菜单类型
 * @returns 类型文本
 */
const getModelTypeText = (modelType?: string) => {
  switch (modelType) {
    case "page":
      return "单页";
    case "list":
      return "列表页";
    case "category":
      return "分类";
    default:
      return "未知";
  }
};

/**
 * 搜索数据
 */
const search = async () => {
  try {
    tableLoading.value = true;
    let params: any = {
      ...formData.value
    };

    // 如果不是展开全部模式，则添加分页参数
    if (!isExpandAll.value) {
      params.pageNum = pages.value.pageNum;
      params.pageSize = pages.value.pageSize;
    }

    const res = await getWebMenuList(params);
    tableData.value = (res as any).data.data || [];
    console.log(tableData.value, "tableData.value");

    treeTableData.value = buildTreeData((res as any).data.data || []);
    console.log(treeTableData.value, "treeTableData");
    pages.value.total = (res as any).data.total || 0;
  } catch (error) {
    ElMessage.error("查询失败");
  } finally {
    tableLoading.value = false;
  }
};

/**
 * 构建树形数据
 * @param data 原始数据
 * @returns 树形数据
 */
const buildTreeData = (data: any[]) => {
  const map = new Map();
  const result: any[] = [];

  // 创建映射
  data.forEach((item) => {
    map.set(item.code, { ...item, children: [] });
  });

  // 构建树形结构
  data.forEach((item) => {
    const node = map.get(item.code);
    if (item.parentCode && map.has(item.parentCode)) {
      const parent = map.get(item.parentCode);
      parent.children.push(node);
      parent.hasChildren = true;
    } else {
      result.push(node);
    }
  });

  return result;
};

/**
 * 展开/折叠全部
 */
const handleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  // 切换展开状态时重新搜索数据
  search();
};

/**
 * 重置搜索
 */
const resetSearch = () => {
  resetForm(formDataRef.value);
  search();
};

/**
 * 处理表格选择变化
 * @param selection 选中的行数据
 */
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

/**
 * 新增菜单
 */
const handleAdd = () => {
  getTemplateOptions();
  isEdit.value = false;
  dialogOptions.value.title = "新增菜单";
  resetDialogForm();
  dialogRef.value.visiableDialog();
};

/**
 * 编辑菜单
 * @param row 行数据
 */
const handleEdit = (row: any) => {
  isEdit.value = true;
  editId.value = row._id;
  dialogOptions.value.title = "编辑菜单";
  diaFormData.value = {
    parentCode: row.parentCode || "",
    parentName: row.parentName || "",
    parentLink: row.parentLink || "",
    code: row.code || "",
    name: row.name || "",
    link: row.link || "",
    modelType: row.modelType || "page",
    modelId: row.modelId || "",
    modelName: row.modelName || "",
    isOutLink: row.isOutLink || 0,
    outLink: row.outLink || "",
    clickable: row.clickable || 1,
    listTplName: row.listTplName || "",
    listTplId: row.listTplId || "",
    detailTplName: row.detailTplName || "",
    detailTplId: row.detailTplId || "",
    icon: row.icon || "",
    picture: row.picture || "",
    title: row.title || "",
    keywords: row.keywords || "",
    description: row.description || "",
    status: row.status || 1,
    sort: row.sort || 0
  };
  // 设置级联选择器的值
  setCascaderValueByParentCode(row.parentCode || "");
  dialogRef.value.visiableDialog();
};

const handlePreview = (row: any) => {
  console.log(row, "预览");

  // window.open(row.link);
};

/**
 * 删除菜单
 * @param row 行数据
 */
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm("菜单删除后，数据将清空，您是否确定要删除该菜单？！", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
    await deleteWebMenu(row._id);
    ElMessage.success("删除成功");
    search();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

/**
 * 切换菜单状态
 * @param row 行数据
 */
const handleToggleStatus = async (row: any) => {
  try {
    const newStatus = row.status === 1 ? 2 : 1;
    await updateWebMenuStatus(row._id, newStatus);
    ElMessage.success("状态更新成功");
    search();
  } catch (error) {
    ElMessage.error("状态更新失败");
  }
};

/**
 * 批量删除
 */
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的数据");
    return;
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的${selectedRows.value.length}条数据吗？`, "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });
    const ids = selectedRows.value.map((row: any) => row._id);
    await batchDeleteWebMenus(ids);
    ElMessage.success("批量删除成功");
    search();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("批量删除失败");
    }
  }
};

/**
 * 重置弹窗表单
 */
const resetDialogForm = () => {
  diaFormData.value = {
    parentCode: "",
    parentName: "",
    parentLink: "",
    code: "",
    name: "",
    link: "",
    modelType: "page",
    modelId: "",
    modelName: "",
    isOutLink: 0,
    outLink: "",
    clickable: 1,
    listTplName: "",
    listTplId: "",
    detailTplName: "",
    detailTplId: "",
    icon: "",
    picture: "",
    title: "",
    keywords: "",
    description: "",
    status: 1,
    sort: 0
  };
  // 清空级联选择器的值
  cascaderValue.value = [];
  // 确保parentName也被清空
  diaFormData.value.parentName = "";
  diaFormDataRef.value?.clearValidate();
};



/**
 * 弹窗确认事件
 */
const handleDialogConfirm = async () => {
  try {
    await diaFormDataRef.value?.validate();

    if (isEdit.value) {
      await updateWebMenu(editId.value, diaFormData.value);
      ElMessage.success("更新成功");
    } else {
      await createWebMenu(diaFormData.value);
      ElMessage.success("创建成功");
    }

    dialogRef.value.invisiableDialog();
    search();
  } catch (error) {
    ElMessage.error(isEdit.value ? "更新失败" : "创建失败");
    dialogRef.value.clearLoading();
  }
};

/**
 * 弹窗关闭事件
 */
const handleDialogClose = () => {
  resetDialogForm();
};

/**
 * 处理级联选择器变化
 * @param value 选中的值
 */
const handleCascaderChange = (value: string[]) => {
  // 级联选择器返回的是数组，需要取最后一个值作为parentCode
  if (Array.isArray(value) && value.length > 0) {
    const selectedCode = value[value.length - 1];

    // 根据选中的code查找对应的菜单信息
    const selectedMenu = findMenuByCode(selectedCode, cascaderOptions.value);

    // 如果当前菜单类型是"单页"，验证选中的父菜单必须是list类型
    if (diaFormData.value.modelType === "page" && selectedMenu && selectedMenu.modelType !== "list" && selectedMenu.code !== "top") {
      ElMessage.error("单页菜单的父菜单必须是列表页或者顶层菜单");
      // 清空选择
      cascaderValue.value = [];
      diaFormData.value.parentCode = "";
      diaFormData.value.parentName = "";
      diaFormData.value.parentLink = "";
      return;
    }

    diaFormData.value.parentCode = selectedCode;

    if (selectedMenu) {
      diaFormData.value.parentName = selectedMenu.name;
      // 如果父菜单有link值，则赋值给parentLink
      if (selectedMenu.link) {
        diaFormData.value.link = selectedMenu.link + "-";
        diaFormData.value.parentLink = selectedMenu.link;
      }
    } else {
      diaFormData.value.parentName = "";
    }
  } else {
    diaFormData.value.parentCode = "";
    diaFormData.value.parentName = "";
    diaFormData.value.parentLink = "";
  }
};

/**
 * 根据code在菜单树中查找菜单项
 * @param code 菜单编码
 * @param menuList 菜单列表
 * @returns 找到的菜单项
 */
const findMenuByCode = (code: string, menuList: any[]): any => {
  for (const menu of menuList) {
    if (menu.code === code) {
      return menu;
    }
    if (menu.children && menu.children.length > 0) {
      const found = findMenuByCode(code, menu.children);
      if (found) {
        return found;
      }
    }
  }
  return null;
};

/**
 * 根据parentCode设置级联选择器的值
 * @param parentCode 父菜单编码
 */
const setCascaderValueByParentCode = (parentCode: string) => {
  if (!parentCode) {
    cascaderValue.value = [];
    return;
  }

  // 根据parentCode查找对应的菜单项并设置parentName
  const selectedMenu = findMenuByCode(parentCode, cascaderOptions.value);
  if (selectedMenu) {
    diaFormData.value.parentName = selectedMenu.name;
  }

  // 这里需要根据parentCode找到完整的路径
  // 简化处理：如果parentCode存在，直接设置为数组
  cascaderValue.value = [parentCode];
};

/**
 * 获取菜单树数据
 */
const getMenuTreeData = async () => {
  try {
    const res = await getMenuTree();
    const menuData = (res.data as any[]) || [];

    // 添加默认的顶层菜单到最上层第一位
    const topLevelMenu = {
      code: "top",
      name: "顶层菜单",
      children: []
    };

    cascaderOptions.value = [topLevelMenu, ...menuData];
  } catch (error) {
    console.error("获取菜单树失败:", error);
  }
};

const getTemplateOptions = async () => {
  try {
    const res = await getAllTemplates();
    pageTemplateOptions.value = (res as any).data.data.filter((item) => ["page", "detail"].includes(item.type)) || [];
    listTemplateOptions.value = (res as any).data.data.filter((item) => item.type === "list") || [];
  } catch (error) {
    console.error("获取模板数据失败:", error);
  }
};

const handleDetailTplIdChange = (value) => {
  const selectedTemplate = pageTemplateOptions.value.find((template) => template._id === value);
  if (selectedTemplate) {
    diaFormData.value.detailTplName = selectedTemplate.templateName;
  }
};

const handleListTplIdChange = (value) => {
  const selectedTemplate = listTemplateOptions.value.find((template) => template._id === value);
  if (selectedTemplate) {
    diaFormData.value.listTplName = selectedTemplate.templateName;
  }
};

// ------- 监听器 -------
/**
 * 监听外部链接变化
 * 当选择外部链接为"是"时，自动设置可点击为"是"
 */
watch(
  () => diaFormData.value.isOutLink,
  (newVal) => {
    if (newVal === 1) {
      diaFormData.value.clickable = 1;
    }
  }
);

/**
 * 监听菜单类型变化
 * 当菜单类型变化时，重新验证菜单链接字段
 */
watch(
  () => diaFormData.value.modelType,
  () => {
    // 如果链接字段有值，重新验证
    if (diaFormData.value.link && diaFormDataRef.value) {
      diaFormDataRef.value.validateField("link");
    }
  }
);

/**
 * 获取所有模块数据
 * 用于填充模型名称下拉选项
 */
const getModulesData = async () => {
  try {
    const res = await getAllModules();
    moduleOptions.value = (res as any).data || [];
  } catch (error) {
    console.error("获取模块数据失败:", error);
    ElMessage.error("获取模块数据失败");
  }
};

/**
 * 处理模型名称选择变化
 * 当选择模型名称时，自动设置对应的模型ID
 * @param modelName 选中的模型名称
 */
const handleModelNameChange = (modelName: string) => {
  if (modelName) {
    // 根据模型名称查找对应的模型ID
    const selectedModule = moduleOptions.value.find((module) => module.moduleName === modelName);
    if (selectedModule) {
      diaFormData.value.modelId = selectedModule.moduleId;
    }
  } else {
    // 清空模型名称时，同时清空模型ID
    diaFormData.value.modelId = "";
  }
};

// ------- 生命周期 -------
onMounted(() => {
  search();
  getMenuTreeData();
  getModulesData();
});
</script>

<style scoped lang="less">
.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.app-container {
  padding: 20px;
}

.mt-3 {
  margin-top: 12px;
}

.w-100 {
  width: 100%;
}

.el-table {
  border-radius: 4px;
}

.el-table .el-table__header-wrapper th {
  background-color: #fafafa;
  color: #606266;
  font-weight: 500;
}

.el-table .el-table__row:hover > td {
  background-color: #f5f7fa;
}
</style>
